var ff = ff || {};
ff.util = {};


ff.util.date = {};
ff.util.date.format = function () {
    if (!Date.prototype.format) {
        Date.prototype.format = function (fmt) {
            var o = {
                'M+': this.getMonth() + 1,
                'd+': this.getDate(),
                'h+': this.getHours(),
                'm+': this.getMinutes(),
                's+': this.getSeconds(),
                'q+': Math.floor((this.getMonth() + 3) / 3),
                'S': this.getMilliseconds()
            }

            if (/(y+)/.test(fmt))
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));

            for (var k in o)
                if (new RegExp('(' + k + ')').test(fmt))

                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));

            return fmt;
        }
    }
};

ff.util.date.format();


ff.util.show = function (message) {
    alert(message);
}

ff.util.rootUrl = function () {
    var curWwwPath = window.document.location.href;

    //获取主机地址之后的目录如：/Tmall/index.jsp 
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);

    //获取主机地址，如： http://localhost:8080 
    var localhostPath = curWwwPath.substring(0, pos);
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
    if (projectName == '/admin') {
        projectName = '';
    }
    //获取带"/"的项目名，如：/Tmall

    return localhostPath + projectName;
}
ff.util.buildUrl = function (url) {
    var abUrl = ff.util.rootUrl();
    if (url.indexOf("/") != 0) {
        url = "/" + url;
    }
    abUrl = abUrl + "/admin" + url;

    return abUrl;
};


ff.util.objToJson = function (obj) {
    return JSON.stringify(obj);
};
ff.util.jsonToObj = function (json) {
    try {
        var obj = JSON.parse(json);
    }
    catch (e) {
        ff.log.error("json convert error", json);
    }
    return obj;
};

ff.util.isSuccess = function (obj) {
    var result = false;
    if (obj.errorCode == 0) {
        result = true;
    }
    return result;
};


ff.util.submit = function (data) {
    debugger;
    if (null == data) {
        ff.log.error("data is null when submit");
        return;
    }
    if ((null != data.data) && (Object.prototype.toString.call(data.data) === "[object String]") && (data.data.indexOf("#") >= 0)) {
//		if ($(data.data).form('validate') == false)      处理form验证
//	    {
//			ff.util.warn("输入验证失败");
//	    	return;
//	    }
        ff.req.obj = $(data.data).serializeObject();
    }
    else if (null != data.data) {
        ff.req.obj = data.data;
    }
    ff.req.filter = data.filter || ff.req.filter;
    ff.req.filter = ff.com.buildFilter(ff.req.filter);
    var json = ff.util.objToJson(ff.req);
    data.url = ff.util.buildUrl(data.url);//+ "?para=" + json;;
    data.data = json;
    var callback = data.success;
    data.success = function (rsp) {
        if (ff.util.isSuccess(rsp)) {
            callback(rsp);
        }
        else {
            ff.util.show(rsp.message);
        }

    };

    ff.util.ajax(data);
};


ff.util.ajax = function (para) {
    try {
        if (para.wait) {
            //showWaitDialog();    //need show wait dialog
        }
        var contentType = "";
        {
            contentType = "application/json";
        }

        $.ajax({
            type: "post",
            url: para.url,
            contentType: contentType,
            data: para.data,
            dataType: "json",
            success: function (data) {
                if (para.wait) {
                    //removeWaitDialog();    //need remove wait dialog
                }
                if (data.errorCode == 10) {
                    //top.location = ff.util.buildPageUrl("Index/Login.html");      //error to login
                }
                para.success(data);
            },
            error: function (error) {
                if (para.wait) {
                    //removeWaitDialog();
                }
                ff.util.show("网路请求失败");
            }
        });
    }
    catch (e) {
        alert(e);
    }
};
ff.util.urlPara = function (key) {
    var name, value;
    var str = location.href; //取得整个地址栏
    str = decodeURI(str);
    var num = str.indexOf("?")
    str = str.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]

    var arr = str.split("&"); //各个参数放到数组里
    var paras = [];
    for (var i = 0; i < arr.length; i++) {
        num = arr[i].indexOf("=");
        if (num > 0) {
            name = arr[i].substring(0, num);
            value = arr[i].substr(num + 1);
            paras[name] = value;
        }
    }
    if (null != key) {
        return paras[key]
    }
    return paras;
};

ff.util.copy = function (obj) {
    var newobj = {};
    for (var attr in obj) {
        newobj[attr] = obj[attr];
    }
    return newobj;
}
ff.cache = {};
ff.cache.set = function (key, value) {

    if (!window.sessionStorage) {
        ff.util.show("please use html5 browser");
        return;
    }

    sessionStorage.setItem(key, ff.util.objToJson(value));
};

ff.cache.get = function (key) {
    if (!window.sessionStorage) {
        alert('please use html5 browser');
        return;
    }
    return ff.util.jsonToObj(sessionStorage.getItem(key));
}

